<template>
	<view class="chat">
		<scroll-view  :style="{height: `${windowHeight-inputHeight - 0}rpx`}" id="scrollview" scroll-y="true"
			:scroll-top="scrollTop" class="scroll-view" :scroll-into-view="scrollIntoIndex"
			:scroll-with-animation="true">
			<!-- 聊天主体 -->
			<view id="msglistview"  class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 时间 -->
					<view
					  class="first-box"
					  v-if="Math.floor(index / 5) * 5 == (index / 5) * 5">
					  <view class="first-time"> 
					    {{item.time}}
					  </view>
					</view>
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.fromid == userInfo.id">
						<!-- 文字内容 -->						 
						<view class="content right img" v-if="isImage(item.data)"  @click="showModal(item.id)">
						   <image  :src="item.data" mode="aspectFill" class="image-content"></image>
						</view>
						<view class="content right" v-else  @click="showModal(item.id)">
						    {{item.data}}
						</view>
						<!-- 头像 -->
						<image class="avatar" :src="userInfo.headimg" mode="aspectFill">
						</image>
					</view>
					<!-- 机器人发的消息 -->
					<view class="item Ai" v-else>
						<!-- 头像 -->
						<image class="avatar" :src="messageTouser.headimg" mode="aspectFill">
						</image>
						 
						<!-- 文字内容 -->
						<view class="content left img" v-if="isImage(item.data)">
						   <image :src="item.data " mode="aspectFill" class="image-content"></image>
						</view>
						<view class="content left" v-else>
					        {{item.data}}
						</view>
						
					</view>
				</view>
			</view>
			
		</scroll-view>
         <u-modal :show="BlockShow" @cancel="cancel" @confirm="confirm" :showCancelButton="true"
					:title="BlockTitle" :content='content'></u-modal>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight - 60}rpx`}">
				<view class="uni-textarea">
					<textarea v-model="chatMsg" maxlength="300" confirm-type="send"
						placeholder="快来聊天吧~" :show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight"
						auto-height></textarea> 
				</view>
				<view class="thumb" >
					<image src="/static/user/photo.png" mode="widthFix"  @click="chooseImage"></image>
				</view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		mapState,
		mapActions
	} from "vuex"
	import {
		uploadFile,
	} from '@/store/upload.js'
	import {
		 timestampToDate
	} from '@/store/upload.js'
	import Ws from '@/utils/socket.js'
	export default {
		data() {
			return {
				BlockShow: false, //拉黑
				BlockTitle: '', //拉黑对话框
				content: '', //拉黑对话框内容
				scrollIntoIndex:"",
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				//报存的高度
				generous:0,
				//发送的消息
				chatMsg: "",
				msgList: [],
				avatarList: {},
				to_avatar: null,
				otherId:null,
				userId:null,
				Received:[],//要过滤的对象
				chid:'',//撤回id
				img:'',//img

			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
			...mapState('user', ['userInfo', 'webSocket', 'messageTouser', 'message']),
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight
			}
			
		},

		onLoad() {
			console.log(this.messageTouser,'我的信息');
		    if(this.messageTouser.toid){
				this.otherId = this.messageTouser.toid
			}else{
				console.log(this.messageTouser.id)
				this.otherId = this.messageTouser.id
			}
			this.userId = this.userInfo.id
			this.loadChatMsg()
			// this.watchMessage()
			// this.curing()
		 
		},
		watch: {
		    message (res) {
				console.log(res);
		        if (res) {
					console.log('监听')
		        	const data = JSON.parse(res.data)
		        	 if (data.type == 'save') {
		        		const objs = {
		        			fromid: data.fromid,
		        			toid: data.toid,
		        			data: data.data,
		        			time: timestampToDate(data.time),
		        			isread: 1,
		        			type: data.type,
		        		}
						console.log(objs,'objs')
		        		this.msgList.push(objs)
						const obj = {
							fromid: data.fromid,
							toid: data.toid,
							data: data.data,
							time: data.time,
							isread: 1,
							type: data.type,
						}
		        		this.$api.saveSmessage(obj).then(res => {
		        			if (res.code != 1) {
		        				uni.showToast({
		        					title: '保存信息失败！',
		        					duration: 2000,
		        				})
		        				return
		        			} else {
		        				this.$nextTick(() => {
		        					this.scrollToBottom()
		        				})
		        			}
		        		})
		        	} else if (data.type == 'text') {
		        		 if (data.isread == 0) {
		        		 	const title = '聊天(离线)';
		        		 	// 设置导航栏标题
		        		 	uni.setNavigationBarTitle({
		        		 	    title: title // 设置的新标题
		        		 	}); 
		        		 } else {
		        		 	const title = '聊天(在线)';
		        		 	// 设置导航栏标题
		        		 	uni.setNavigationBarTitle({
		        		 	    title: title // 设置的新标题
		        		 	});	 
		        		 }
		        		if (data.toid == this.userId) {
		        			if (data.fromid == this.otherId) {
		        				const obj = {
		        					fromid: data.fromid,
		        					toid: data.toid,
		        					data: data.data,
		        					time: timestampToDate(data.time),
		        					isread: 1,
		        					type: data.type,
		        				}
		        				this.msgList.push(obj)
		     
		        			}
		        		}
		        	} else if (data.type == 'online') {
		        		// console.log('获取的online', data)
		        		 const title = data.isread == 0 ? '聊天(离线)' : '聊天(在线)';
		        		 uni.setNavigationBarTitle({ title });
		        		                 
		        
		        	}
		        }
		    }
			
		},

		methods: {
			 isImage(data) {
			      // 判断 data 是否为图片链接
			      return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(data);
			    },
			showModal(id) {
				this.chid = id
				this.BlockShow = true;
				this.BlockTitle = '是否确认撤回聊天信息';
			},
			confirm() {
				this.BlockShow = false
				this.revocation()
			},
			cancel() {
				this.BlockShow = false
			
			},
			//撤回信息
			revocation(){
				this.$api.Retraction({id:this.chid}).then(res=>{
					console.log(res,'res')
					this.loadChatMsg()
				})
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight() {
				// 在uniapp中监听软键盘的弹出事件
				uni.onKeyboardHeightChange(res => {
				  if (res.height > 0) {
					  this.generous = this.inputHeight
					  this.keyboardHeight = res.height + this.inputHeight + Number(80)
				  } else {
					  this.inputHeight = this.generous
					  this.keyboardHeight = 0
				  }
				});
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 10)
			},
			// 滚动至聊天底部
			scrollToBottom(e) {
				console.log(111);
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 15)
			},
			// 获取过滤信息
			// curing(){
			// 	this.$api.sensitive().then(res=>{
			// 		this.Received = res.data
			// 	})
			// },
			//发送图片
		async chooseImage() {
		    try {
		        const res = await new Promise((resolve, reject) => {
		            uni.chooseImage({
		                success: resolve,
		                fail: reject
		            });
		        });
		
		        // 上传文件
		        const result = await uploadFile([res.tempFilePaths[0]]);
		        console.log(result, '上传结果');
		
		        this.img = result[0];
		        console.log(this.img, '图片');
		
		        // 发送消息
		        const obj = {
		            data: {
		                type: 'say_img',
		                data: this.img,
		            },
		            type: 'say',
		            from_id: this.userId,
		            to_id: this.otherId,
		        };
		
		        console.log(11, '发送图片');
		        this.webSocket.socketTask.send({
		            data: JSON.stringify(obj),
		        });
		
		        // 清空 img
		        this.img = '';
		
		    } catch (error) {
		        console.error('选择或上传图片时出错:', error);
		    }
		},
			// 发送消息
			async handleSend() {
				// const isInvalid = this.Received.some(item => this.chatMsg.includes(item));
				// if (isInvalid) {
				// 	uni.showToast({
				// 		title: '输入的消息不能包含已存在的关键词！',
				// 		icon: 'none',
				// 	})
				// 	return 
				// }
				console.log(this.chatMsg,'this.chatMsg')
				if (this.chatMsg) {
					let obj = {
						data: {
							type: 'text',
							data: this.chatMsg,
						},
						type: 'say',
						from_id: this.userId,
						to_id: this.otherId,
					}
					console.log(11,'我的')
					this.webSocket.socketTask.send({
						data: JSON.stringify(obj),
					})
					this.chatMsg = ''
					 			
				} else {
					uni.showToast({
						title: '请输入信息',
						icon: 'none',
					})
				}
			},
			//处理接收的信息
			onMessage(res) {
				
			},
			async loadChatMsg() {
				const res = await this.$api.loaDmessage({
					fromid: this.userId,
					toid: this.otherId,
				}).then(res => {
					this.msgList = res.data.data.reverse()
					if (this.msgList.length > 0) {
						this.$nextTick(() => {
							
							this.scrollIntoIndex = 'chat_' + (this.msgList.length - 1)
							this.scrollToBottom()
						})
					}
				})
				const ress = await this.$api.UpdateUnread({
					fromid: this.otherId,
					toid: this.userId,
				}).then(res => {
				
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* 聊天消息 */
	.chat {

		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;
               .first-box {
                 padding: 20rpx 0;
                 .first-time {
                   text-align: center;
                   color: #7d8799;
                     }
               }
				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}
					.img{
						background-color:#f6f6f6;
						 .image-content{
							 max-width: 100%; /* 根据需要调整 */
							   max-height: 200px; /* 根据需要调整 */
							   display: block;
						 }
					}

					.left {
						background-color: #FFFFFF;
					}

					// 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 50rpx;
						overflow: hidden;

						image {
							align-self: center;
						}

					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 100rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;
			

			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 10rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #fff;
				transition: all 0.1s ease;
			}

			.uni-textarea {
				padding-bottom: 70rpx;
				textarea {
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #f1f1f1;
					border-radius: 40rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 74rpx;
					padding: 5rpx 8rpx;
					text-indent: 30rpx;
				}
			}
			.thumb {
				width: 100rpx;
				height: 64rpx;
				margin-bottom: 76rpx;
				margin-left: 15rpx;
				image{
				width: 64rpx;
				height: 64rpx;
				min-height: 75rpx;
				display: block;	
				}
			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 76rpx;
				margin-left:0rpx;
				width: 120rpx;
				height: 75rpx;
				background: #ed5a65;
				border-radius: 50rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}
	}
</style>